﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using DECOR.DL.DALC.SAPC.Proxy;
using CroslandSAP.Proxy;
using System.Data;
using CROSLAND.BL.BE;

namespace CROSLAND.DL.DALC.SAPC
{
    public class ClienteDALC : IClienteDALC
    {
        public static ClienteDALC Instance()
        {
            if (_instance == null)
            {
                lock (typeof(ClienteDALC))
                {
                    if (_instance == null)
                    {
                        _instance = new ClienteDALC();
                    }
                }
            }
            return _instance;
        }
        private ClienteDALC() { }
        private static volatile ClienteDALC _instance = null;


        #region IClienteDALC Members

        public List<InterlocutorBE> buscaInterlocutores(string pCodCliente, string pCodOrgVtas, string pCodCanalDist, string pSector)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            /* llamando a la función */
            ZSSD_CLIENTETable tblResult = new ZSSD_CLIENTETable();
            proxy.Zvmc_Sd_005(pCodCliente, pSector, pCodOrgVtas, pCodCanalDist, ref tblResult);
            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;

            DataTable dt = tblResult.ToADODataTable();
            List<InterlocutorBE> listaResult = new List<InterlocutorBE>();
            InterlocutorBE objInterlocutor = null; ClienteBE obj = null; PersonaBE objPer = null; string strCodPersona = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                obj = new ClienteBE();
                obj.Codigo = dr["KUNNR"].ToString();
                obj.Descripcion = dr["NAME1"].ToString().Trim() + (dr["NAME2"].ToString().Trim().Equals("") ? "" : " " + dr["NAME2"].ToString());
                obj.Ruc = dr["STCD1"].ToString();
                obj.NOMBRE = dr["NAME1"].ToString().Trim();
                obj.APPAT = (dr["NAME2"].ToString().Trim().Equals("") ? "" : " " + dr["NAME2"].ToString());
                obj.tipoNif = dr["STCDT"].ToString();
                obj.nif = dr["STCD1"].ToString();
                obj.Direccion = dr["STRAS"].ToString();
                obj.Distrito = dr["ORT02"].ToString();
                obj.Ciudad = dr["ORT01"].ToString();
                obj.poblacion = dr["ORT01"].ToString().TrimStart('0');
                obj.region = dr["REGIO"].ToString();
                obj.Telefono = dr["TELF1"].ToString();
                obj.zonaRegistral = dr["KUKLA"].ToString();
                obj.grupoCliente = dr["KVGR1"].ToString();
                obj.moneda = dr["WAERS"].ToString();
                obj.oficinaVentas = dr["VKBUR"].ToString();
                obj.Mail = dr["SMTP_ADDR"].ToString();
                if (dr["XCPDK"].ToString().Equals("X")) { obj.Eventual = true; } else { obj.Eventual = false; }
                obj.vend_code = dr["VEND_CODE"].ToString();
                obj.vend_text = dr["VEND_TEXT"].ToString();
                obj.cond_pago = dr["ZTERM"].ToString();

                objInterlocutor = new InterlocutorBE();
                strCodPersona = obj.vend_code.Trim();
                if (string.IsNullOrEmpty(strCodPersona) || strCodPersona.Equals("00000000"))
                {
                    objInterlocutor.Cliente = obj;
                }
                else
                {
                    objPer = new PersonaBE();
                    objPer.CodPersona = obj.vend_code;
                    objPer.Descripcion = obj.vend_text;
                    objInterlocutor.Persona = objPer;
                }
                objInterlocutor.Funcion = dr["PARVW"].ToString();

                listaResult.Add(objInterlocutor);
            }
            return listaResult;
        }

        public string validaRUC(string pRuc, string pOrgVtas)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            //-----------------
            string ex_result = "";
            //proxy.Zweb_Validar_Ruc(pOrgVtas, pRuc, out ex_result);
            //-----------------
            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;
            return ex_result;
        }

        public List<GenericBE> buscaVendedor(string txtVen, string codVen, string ofVta, DateTime fecha)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            /* llamando a la función */
            DYCBOXTable tblResult = new DYCBOXTable();
            string fec = ParametroDALC.dateNetToSap(fecha);
            
            proxy.Zvmc_Sd_042(fec, txtVen, codVen, ofVta, ref tblResult);

            /* Manejando el retorno */
            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;

            List<GenericBE> listaResult = new List<GenericBE>();
            foreach (DYCBOX itm in tblResult)
            {
                GenericBE obj = new GenericBE();
                obj.Codigo = itm.Fieldname;
                obj.Descripcion = itm.Helpid;
                listaResult.Add(obj);
            }
            return listaResult;
        }

        public List<ClienteBE> buscarEntFin(string pCodigo, string pNombre, UsuarioWebBE uw)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            /* llamando a la función */
            ZSSD_CLIENTETable tblResult = new ZSSD_CLIENTETable();
            proxy.Zvmc_Sd_038(uw.CanalDist, 50, pCodigo, pNombre, uw.OrgVentas, uw.sector, "", ref tblResult);

            /* Manejando el retorno */
            DataTable dt = tblResult.ToADODataTable();
            if (dt.Rows.Count == 0)
            {
                proxy.Zvmc_Sd_038(uw.CanalDist, 50, "", pNombre, uw.OrgVentas, uw.sector, pCodigo, ref tblResult);
                dt = tblResult.ToADODataTable();
            }

            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;

            List<ClienteBE> listaResult = new List<ClienteBE>();
            foreach (DataRow dr in dt.Rows)
            {
                ClienteBE obj = new ClienteBE();
                obj.Codigo = dr["KUNNR"].ToString();
                obj.Descripcion = dr["NAME1"].ToString().Trim() + (dr["NAME2"].ToString().Trim().Equals("") ? "" : " " + dr["NAME2"].ToString());
                obj.NOMBRE = dr["NAME1"].ToString().Trim();
                obj.APPAT = (dr["NAME2"].ToString().Trim().Equals("") ? "" : " " + dr["NAME2"].ToString());

                listaResult.Add(obj);
            }
            return listaResult;
        }

        public List<ClienteBE> buscarCliente(string pCodigo, string pNombre, UsuarioWebBE uw)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            /* llamando a la función */
            ZSSD_CLIENTETable tblResult = new ZSSD_CLIENTETable();
            proxy.Zvmc_Sd_002(uw.CanalDist, 50, pCodigo, pNombre, uw.OrgVentas, uw.sector, "", ref tblResult);
            
            /* Manejando el retorno */
            DataTable dt = tblResult.ToADODataTable();
            if (dt.Rows.Count == 0)
            {
                proxy.Zvmc_Sd_002(uw.CanalDist, 50, "", pNombre, uw.OrgVentas, uw.sector, pCodigo, ref tblResult);
                dt = tblResult.ToADODataTable();
            }

            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;

            List<ClienteBE> listaResult = new List<ClienteBE>();
            foreach (DataRow dr in dt.Rows)
            {
                ClienteBE obj = new ClienteBE();
                obj.Codigo = dr["KUNNR"].ToString();
                obj.Descripcion = dr["NAME1"].ToString().Trim() + (dr["NAME2"].ToString().Trim().Equals("") ? "" : " " + dr["NAME2"].ToString());
                obj.Ruc = dr["STCD1"].ToString();
                obj.NOMBRE = dr["NAME1"].ToString().Trim();
                obj.APPAT = (dr["NAME2"].ToString().Trim().Equals("") ? "" : " " + dr["NAME2"].ToString());
                obj.tipoNif = dr["STCDT"].ToString();
                obj.nif = dr["STCD1"].ToString();
                obj.Direccion = dr["STRAS"].ToString();
                obj.Distrito = dr["ORT02"].ToString();
                obj.Ciudad = dr["ORT01"].ToString();
                obj.poblacion = dr["ORT01"].ToString().TrimStart('0');
                obj.region = dr["REGIO"].ToString();
                obj.Telefono = dr["TELF1"].ToString();
                obj.zonaRegistral = dr["KUKLA"].ToString();
                obj.grupoCliente = dr["KVGR1"].ToString();
                obj.moneda = dr["WAERS"].ToString();
                obj.oficinaVentas = dr["VKBUR"].ToString();
                obj.Mail = dr["SMTP_ADDR"].ToString();
                if (dr["XCPDK"].ToString().Equals("X")) { obj.Eventual = true; } else { obj.Eventual = false; }
                obj.vend_code = dr["VEND_CODE"].ToString();
                obj.vend_text = dr["VEND_TEXT"].ToString();
                obj.cond_pago = dr["ZTERM"].ToString();
                obj.Mcod3 = dr["MCOD3"].ToString();
                listaResult.Add(obj);
            }
            return listaResult;
        }

        /// <summary>
        /// Creación de un cliente
        /// </summary>
        /// <param name="objCli">Objeto Cliente</param>
        /// <returns></returns>
        public string creaCliente(ClienteBE objCli, UsuarioWebBE usrWeb, out string codCli)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }

            BAPIADDR1 strAddr = new BAPIADDR1();
            KNA1 strKna1 = new KNA1();
            KNB1 strKnb1 = new KNB1();
            KNVV strKnvv = new KNVV();
            FKNVITable tabKnvi = new FKNVITable();
            FKNVPTable tabKnvp = new FKNVPTable();
            FKNVP strKnvp = new FKNVP();

            strKna1.Ktokd = "ZCLI";
            strKna1.Kukla = objCli.zonaRegistral;
            strKna1.Stcd1 = objCli.nif;
            strKna1.Stcdt = objCli.tipoNif;
            if (objCli.tipoNif != "06")
            {
                strKna1.Stkzn = "X";    
            }
            else
            {
                strKna1.Stkzn = string.Empty;    
            }
            

            strKnb1.Bukrs = usrWeb.sociedad;

            strKnvv.Vkorg = usrWeb.OrgVentas;
            strKnvv.Vkbur = usrWeb.OfVentas;
            strKnvv.Vkgrp = usrWeb.GrpVend;
            strKnvv.Waers = objCli.moneda == null ? objCli.moneda = "PEN" : objCli.moneda == "" ? objCli.moneda = "PEN" : objCli.moneda;
            strKnvv.Kvgr1 = objCli.grupoCliente;
            strKnvv.Kvgr2 = "002";

            strAddr.Name = objCli.NOMBRE;
            strAddr.Name_2 = objCli.APPAT; //es apellido paterno y materno
            strAddr.City = objCli.Ciudad;
            strAddr.District = objCli.Distrito;
            strAddr.Street = objCli.Direccion;
            strAddr.Region = objCli.region;
            strAddr.Tel1_Numbr = objCli.Telefono;
            strAddr.E_Mail = objCli.Mail;

            strKnvp.Vkorg = usrWeb.OrgVentas;
            strKnvp.Pernr = usrWeb.PerNr;
            tabKnvp.Add(strKnvp);

            codCli = "";
            string result = "";
            proxy.Zvmc_Sd_009(strAddr, strKna1, strKnb1, strKnvv, out codCli, out result, ref tabKnvi, ref tabKnvp);
            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;
            return result;
        }

        public string modificaCliente(ClienteBE objCli, UsuarioWebBE usrWeb)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            BAPIRETURN1 t_Return = new BAPIRETURN1();
            string msg;
            BAPIKNA106 strK = new BAPIKNA106();
            strK.Name = objCli.NOMBRE;
            strK.Name_2 = objCli.APPAT;
            strK.City = objCli.Ciudad;
            strK.District = objCli.Distrito;
            strK.Street = objCli.Direccion;
            strK.Region = objCli.region;
            strK.Tel1_Numbr = objCli.Telefono;
            strK.E_Mail = objCli.Mail;
            strK.Currency = objCli.moneda == "" ? objCli.moneda = "PEN" : objCli.moneda;

            proxy.Zvmc_Sd_015(usrWeb.CanalDist, objCli.Codigo, strK, usrWeb.OrgVentas, out t_Return);
            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;
            msg = t_Return.Message;
            return msg;
        }

        public List<ClienteBE.BancoBE> listaBanco(string codCliente, string soc)
        {
            ClientesProxy proxy = new ClientesProxy();
            proxy.Connection = DALC.getConnection;
            if (!proxy.Connection.IsOpen) { proxy.Connection.Open(); }
            DYCBOXTable dy = new DYCBOXTable();
            proxy.Zvmc_Sd_045(soc, codCliente, ref dy);
            SAP.Connector.SAPConnectionPool.ReturnConnection(proxy.Connection);
            proxy.Connection = null;
            List<ClienteBE.BancoBE> lstResutl = new List<ClienteBE.BancoBE>();
            ClienteBE.BancoBE banco;
            foreach (DYCBOX tbl in dy)
            {
                banco = new ClienteBE.BancoBE();
                banco.codCliente = codCliente;
                banco.banco = tbl.Fieldname;
                banco.txtBanco = tbl.Helpid;
                banco.credipago = tbl.Vrmid;
                lstResutl.Add(banco);
            }
            return lstResutl;
        }

        #endregion
    }
}
